package lg.iu.transforms;

import lg.iu.ClassHooks;
import lg.iu.FieldHooks;

import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FieldNode;

import wolf.iu.framework.ClassContainer;
import wolf.iu.framework.ClassesHandler;
import wolf.iu.framework.HooksList;
import wolf.iu.framework.hooks.AbstractClassHookEnum;
import wolf.iu.framework.hooks.DependencyTransform;
import wolf.iu.framework.hooks.HookState;

public class InterfaceCacheFinder extends DependencyTransform {

    @Override
    public HookState execute(final ClassesHandler ch, final ClassContainer cc,
            final HooksList hooks) {
        
        final String ifaceClazz = hooks.getHook(ClassHooks.Interface).getFullOldName();
        
        int nonstaticFields = 0;
        
        FieldNode pField = null;
        
        for (final Object o : cc.getNode().fields) {
            final FieldNode field = (FieldNode) o;
            if (field.desc.equals("[[L" + ifaceClazz + ";")) {
                pField = field;
            }
            if ((field.access & Opcodes.ACC_STATIC) == 0) {
                nonstaticFields++;
            }
        }
        if (pField != null && nonstaticFields > 1) {
            hooks.setFieldHook(ClassHooks.Client, FieldHooks.GetIFaceCache,
            new FieldInsnNode(Opcodes.GETSTATIC, cc.getName(), pField.name, pField.desc));
            return HookState.Found;
        }
        
        return HookState.NotFound;
    }

    @Override
    public AbstractClassHookEnum dependency() {
        return ClassHooks.Interface;
    }

}
